﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Marmat.Forms.Skin
{
    public class DropDownControlHost
    {
        private System.Windows.Forms.ToolStripControlHost ToolStripControlHost { get; set; }

        private System.Windows.Forms.ToolStripDropDown m_toolStripDropDown;
        private readonly Control control;

        public DropDownControlHost(Control control)
        {
            this.control = control;
        }

        /// <summary>
        /// 在打开 System.Windows.Forms.ToolStripDropDown 时发生。
        /// </summary>
        [Category("CatAction")]
        [Description("ToolStripDropDownOpenedDescr")]
        public event EventHandler Opened;

        /// <summary>
        /// System.Windows.Forms.ToolStripDropDown 控件正打开时发生。
        /// </summary>
        [Category("CatAction")]
        [Description("ToolStripDropDownOpeningDescr")]
        public event CancelEventHandler Opening;

        private System.Windows.Forms.ToolStripDropDown ToolStripDropDown
        {
            get
            {
                if (m_toolStripDropDown is null)
                {
                    m_toolStripDropDown = new System.Windows.Forms.ToolStripDropDown();
                    m_toolStripDropDown.DropShadowEnabled = false;
                    m_toolStripDropDown.Padding = new Padding(1, 0, 1, 0);
                    m_toolStripDropDown.AutoClose = false;

                }
                return m_toolStripDropDown;
            }
        }



        /// <summary>
        /// 显示下拉窗体
        /// </summary>
        public void ShowDropDown(Control control)
        {
            ShowDropDown(control, new Point(0, control.Height));
        }

        /// <summary>
        /// 显示下拉窗体
        /// </summary>
        public void ShowDropDown(Control control, Point position)
        {
            if (this.ToolStripDropDown.Items.Count == 0 && this.control != null && ToolStripDropDown.IsDisposed == false)
            {
                this.ToolStripDropDown.Dock = DockStyle.Fill;
                this.ToolStripControlHost = new System.Windows.Forms.ToolStripControlHost(this.control);
                ToolStripControlHost.AutoSize = false;
                ToolStripDropDown.Items.Add(ToolStripControlHost);
                ToolStripDropDown.Tag = this;
            }
            if (this.control != null)
            {
                ToolStripControlHost.Width = control.Width;
                m_toolStripDropDown.Show(control, position);
            }
        }

        /// <summary>
        /// 关闭下拉窗口
        /// </summary>
        public void CloseDropDown()
        {
            if (this.ToolStripDropDown != null)
            {
                this.ToolStripDropDown.Close();
            }
        }
    }
}
